package com.xdtech.hotel.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xdtech.core.dao.BaseDao;
import com.xdtech.core.model.BaseItem;
import com.xdtech.core.orm.Page;
import com.xdtech.core.orm.utils.BeanUtils;
import com.xdtech.hotel.dao.ProtocolCmdDao;
import com.xdtech.hotel.model.ProtocolCmd;
import com.xdtech.hotel.protocol.vo.RCUDevice;
import com.xdtech.hotel.service.ProtocolCmdService;
import com.xdtech.hotel.service.RoomService;
import com.xdtech.hotel.util.HotelConstants;
import com.xdtech.hotel.vo.ProtocolCmdItem;
import com.xdtech.hotel.vo.RoomItem;
import com.xdtech.web.model.Pagination;

/**
 * 
 * @author max.zheng
 * @create 2015-05-25 21:41:22
 * @since 1.0
 * @see
 */
@Service
public class ProtocolCmdServiceImpl implements ProtocolCmdService {
	private Log log = LogFactory.getLog(ProtocolCmdServiceImpl.class);
	@Autowired
	private ProtocolCmdDao protocolCmdDao;
	@Autowired
	private BaseDao baseDao;
	@Autowired
	private RoomService roomService;
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param entity
	 */
	public void save(ProtocolCmd entity) {
		protocolCmdDao.save(entity);
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param entity
	 */
	public void saveAll(List<ProtocolCmd> entities) {
		protocolCmdDao.saveAll(entities);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param entity
	 */
	public void delete(ProtocolCmd entity) {
		protocolCmdDao.delete(entity);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param id
	 */
	public void delete(Long id) {
		protocolCmdDao.delete(id);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param id
	 * @return
	 */
	public ProtocolCmd get(Long id) {
		return protocolCmdDao.get(id);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @return
	 */
	public List<ProtocolCmd> getAll() {
		return protocolCmdDao.getAll();
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param pg
	 * @param values
	 * @return
	 */
	public Map<String, Object> loadPageAndCondition(Pagination pg,
			Map<String, String> values) {
		Map<String, Object> results = new HashMap<String, Object>();
		List<Object> protocolCmds = null;
		long rows = 0;
		if (pg!=null) {
			Page<ProtocolCmd> page = protocolCmdDao.findPage(pg,"from ProtocolCmd order by createTime desc", values);
			protocolCmds = BeanUtils.copyListProperties(
					ProtocolCmdItem.class, page.getResult());
			rows = page.getTotalItems();
		}else {
			List<ProtocolCmd> protocolCmdList = protocolCmdDao.find("from ProtocolCmd order by id desc", values);
			protocolCmds = BeanUtils.copyListProperties(
					ProtocolCmdItem.class, protocolCmdList);
			rows = protocolCmds.size();
		}
		results.put("total", rows);
		results.put("rows", protocolCmds);
		return results;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param item
	 * @return
	 */
	public boolean saveOrUpdateProtocolCmd(ProtocolCmdItem item) {
		ProtocolCmd protocolCmd = null;
		if (item.getId()==null) {
			protocolCmd = new ProtocolCmd();
		}else {
			protocolCmd = protocolCmdDao.get(item.getId());
		}
		//复制前台修改的属性
		BeanUtils.copyProperties(protocolCmd, item);
		protocolCmdDao.save(protocolCmd);
		return true;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param protocolCmdId
	 * @return
	 */
	public ProtocolCmdItem loadProtocolCmdItem(Long protocolCmdId) {
		ProtocolCmd protocolCmd = protocolCmdDao.get(protocolCmdId);
		ProtocolCmdItem protocolCmdItem = new ProtocolCmdItem();
		BeanUtils.copyProperties(protocolCmdItem, protocolCmd);
		return protocolCmdItem;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param id
	 * @return
	 */
	public boolean deleteProtocolCmdInfo(long id) {
		delete(id);
		return true;
	}
	
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @param newIds
	 * @return
	 */
	public boolean deleteProtocolCmdInfo(List<Long> protocolCmdIds) {
		for (Long id : protocolCmdIds) {
			delete(id);
		}
		return true;
	}
	
	public Map<String, Object> loadPageDataByConditions(Pagination pg,
			BaseItem baseItem, String queryName) {
		Map<String, Object> results = new HashMap<String, Object>();
		Page page = baseDao.findPageByNamedQuery(pg, queryName,baseItem);
		results.put("total", page.getTotalItems());
		results.put("rows", page.getResult());
		return results;
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-05-25 21:41:22
	 * @modified by
	 * @return
	 */
	@Override
	public List<ProtocolCmdItem> loadItems() {
		List<ProtocolCmd> protocolCmds = getAll();
		return ProtocolCmdItem.createItems(protocolCmds);
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-5-25下午11:15:57
	 * @modified by
	 * @param device
	 * @param cmdId
	 */
	@Override
	public void secondResultHandler(RCUDevice device,String sendData,String returnData,Long cmdId) {
		ProtocolCmd protocolCmd = get(cmdId);
	    protocolCmd.setSecondResult(returnData);
	    if (checkResult(device, sendData+"#"+returnData)) {
	    	protocolCmd.setResult("success");
		}else {
			protocolCmd.setResult("fail");
		}
	    save(protocolCmd);
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-7-16下午11:01:59
	 * @modified by
	 * @param device
	 * @param temps
	 * @return
	 */
	@Override
	public boolean checkResult(RCUDevice device, String sendDataAndreturnData) {
		boolean rs = true;
		String[] tempArray = sendDataAndreturnData.split("#");
		String sendData = tempArray[0];
		String returnData = tempArray[1];
		try {
			if (sendData.contains("write")&&returnData.contains("ack_w")) {
				Map<String, String> checkMap = getSendMap(sendData);
				Map<String, String> returnMap = getReturnMap(device,returnData,checkMap);
				for (String key : checkMap.keySet()) {
					if (!("true").equals(returnMap.get(key))) {
						//不返回true
						rs = false;
					}
				}
			}else if (sendData.contains("read")&&returnData.contains("ack_r")) {
				//软件读操作
			}else {
				rs = false;
			}
		} catch (Exception e) {
			log.error("write cmd return  处理失败：",e);
			rs = false;
		}
		
		
		return rs;
	}
	
	private Map<String, String> getSendMap(String sendData) throws Exception {
		Map<String, String> checkMap = new HashMap<String, String>();
		//软件写操作
		org.codehaus.jettison.json.JSONObject sendJson = new org.codehaus.jettison.json.JSONObject(sendData);
		JSONArray compArray = sendJson.getJSONArray("write");
		
		for (int i = 0; i < compArray.length(); i++) {
			org.codehaus.jettison.json.JSONObject compJson = compArray.getJSONObject(i);
			String nodeType = getNodeType(compJson);
			//包含节点的返回值
			JSONArray nodeArray = compJson.getJSONArray(nodeType);
			for (int j = 0; j < nodeArray.length(); j++) {
				org.codehaus.jettison.json.JSONObject nodeJson = nodeArray.getJSONObject(j);
				String key = "";
				if (nodeJson.has("addr")) {
					key = nodeType+"_"+nodeJson.getString("addr")+"_"+nodeJson.getString("channel");
				}else {
					key = nodeType;
				}
				//设置每个控制信息
				checkMap.put(key, nodeJson.toString());
			}
		}
		return checkMap;
	}
	
	private Map<String, String> getReturnMap(RCUDevice device,String returnData,Map<String, String> checkMap) throws Exception {
		Map<String, String> rsMap = new HashMap<String, String>();
		if (returnData.contains("SN")) {
			//软件写操作,设备返回
			org.codehaus.jettison.json.JSONObject sendJson = new org.codehaus.jettison.json.JSONObject(returnData);
			JSONArray compArray = sendJson.getJSONArray("ack_w");
			
			for (int i = 0; i < compArray.length(); i++) {
				org.codehaus.jettison.json.JSONObject compJson = compArray.getJSONObject(i);
				String nodeType = getNodeType(compJson);
				//包含节点的返回值
				JSONArray nodeArray = compJson.getJSONArray(nodeType);
				for (int j = 0; j < nodeArray.length(); j++) {
					org.codehaus.jettison.json.JSONObject nodeJson = nodeArray.getJSONObject(j);
					//设置每个控制信息
					String key = "";
					if (nodeJson.has("addr")) {
						key = nodeType+"_"+nodeJson.getString("addr")+"_"+nodeJson.getString("channel");
					}else {
						key = nodeType;
					}
					
					rsMap.put(key, nodeJson.getString("success"));
					//
					if("true".equals(nodeJson.getString("success"))) {
						if (checkMap.containsKey(key)) {
							roomService.updateRoomInfo(device.getSn(),checkMap.get(key),nodeType);
						}else {
							log.error("write cmd addr and channel is diffent,write comp=:"+checkMap+",return is="+key);
						}
						
					}
				}
			}
		}
		return rsMap;
	}
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-7-16下午11:28:34
	 * @modified by
	 * @param compJson
	 * @return
	 * @throws Exception 
	 */
	private String getNodeType(org.codehaus.jettison.json.JSONObject compJson) throws Exception {
		if (compJson.has(HotelConstants.DEV_NODE_CONTROL)) {
			return HotelConstants.DEV_NODE_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_AC_CONTROL)) {
			return HotelConstants.DEV_AC_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_CARD_CONTROL)) {
			return HotelConstants.DEV_CARD_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_DIMMER_CONTROL)) {
			return HotelConstants.DEV_DIMMER_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_MUSIC_CONTROL)) {
			return HotelConstants.DEV_MUSIC_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_TV_CONTROL)) {
			return HotelConstants.DEV_TV_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_CARD_CONTROL)){
			return HotelConstants.DEV_CARD_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_SCENE_CONTROL)){
			return HotelConstants.DEV_SCENE_CONTROL;
		}else if (compJson.has(HotelConstants.DEV_TIME_CONTROL)){
			return HotelConstants.DEV_TIME_CONTROL;
		}
		return null;
	}

}
